package com.czxy.filter;

import czxy.util.JWTUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Order(-1)
public class AuthFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1 获取request
        ServerHttpRequest request = exchange.getRequest();
        //2 获取请求路径url
        String path = request.getURI().getPath();
        //3 判断url是放行还是拦截:1、/auth登录  放行 2、/search搜索  放行 /3、/user 新增用户 拦截
        if (path.contains("/auth")||path.contains("/product")||path.contains("/brand")||path.contains("/category")){
            System.out.println("无需拦截，直接放行");
            return  chain.filter(exchange);
        }
        //4 拦截的需要做如下获取：获取请求头中的token
        List<String> tokens = request.getHeaders().get("authorization");
        //5 判断token是否为空--
        if (tokens!=null&&tokens.size()>0){
            //6 不为空，解析token
            String token = tokens.get(0);
            Claims claims = JWTUtil.parseToken(token, "user");
            if (claims!=null){
                //权限认证通过 //7 解析的token不为空，那就是权限校验通过
                return  chain.filter(exchange);
            }
        }
        //8 否则，全部失败
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();

    }
}
